import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_frontend/environment_config.dart';
import 'package:flutter_frontend/http/mine_api.dart';
import 'package:flutter_frontend/models/list_title_model.dart';
import 'package:flutter_frontend/pages/mine/upgrade_model.dart';
import 'package:flutter_frontend/utils/app_manager.dart';
import 'package:flutter_frontend/utils/assets_path.dart';
import 'package:flutter_frontend/utils/http_manager.dart';
import 'package:flutter_frontend/widgets/my_dialog.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:network_logger/network_logger.dart';
import 'package:package_info_plus/package_info_plus.dart';

class AboutPage extends StatefulWidget {
  const AboutPage({Key? key}) : super(key: key);

  @override
  State<AboutPage> createState() => _AboutPageState();
}

class _AboutPageState extends State<AboutPage> {
  final List<ListTitleModel> _settingsList = [];
  String? _currentVersion;

  @override
  void initState() {
    super.initState();
    Future.microtask(() async {
      final PackageInfo packageInfo = await PackageInfo.fromPlatform();
      _currentVersion = EnvironmentConfig.isRelease ? 'V ${packageInfo.version}' : 'V ${packageInfo.version}.${packageInfo.buildNumber}';
      _settingsList.add(
        ListTitleModel(
          id: 0,
          title: '检查更新',
          onTap: () async {
            dynamic value = await MineApi.checkAppVersion();
            if (value is String) {
              EasyLoading.showToast(value);
            } else if (value is UpgradeModel) {
              MyDialog.showUpgradeDialog(context, value);
            }
          },
        ),
      );
      if (!EnvironmentConfig.isRelease) {
        _settingsList.addAll([
          ListTitleModel(
            id: 1,
            title: '接口查看工具',
            iconPath: 'icon_change_password',
            onTap: () {
              Overlay.of(context).insert(OverlayEntry(builder: (context) {
                return Align(alignment: Alignment.topRight, child: NetworkLoggerButton());
              }));
            },
          ),
        ]);
        final String hostUrl = await HttpManager().hostUrl;
        final List<ListTitleModel> hostList = [
          ListTitleModel()
            ..title = '开发'
            ..subTitle = EnvironmentConfig.baseUrlDevelop
            ..value = 'DEVELOP',
          ListTitleModel()
            ..title = '测试'
            ..subTitle = EnvironmentConfig.baseUrlTest
            ..value = 'TEST',
          ListTitleModel()
            ..title = '准生产'
            ..subTitle = EnvironmentConfig.baseUrlProd
            ..value = 'PROD',
        ];
        _settingsList.addAll([
          ListTitleModel(
            id: 2,
            title: '切换域名',
            value: hostUrl,
            iconPath: 'icon_change_password',
            onTap: () {
              showModalBottomSheet(
                context: context,
                builder: (context) {
                  return Container(
                    padding: const EdgeInsets.symmetric(vertical: 24).w,
                    color: Theme.of(context).colorScheme.background,
                    child: ListView.separated(
                      shrinkWrap: true,
                      physics: const NeverScrollableScrollPhysics(),
                      itemBuilder: (BuildContext context, int index) {
                        final ListTitleModel model = hostList[index];
                        return InkWell(
                          child: Padding(
                            padding: const EdgeInsets.symmetric(horizontal: 48, vertical: 24).w,
                            child: Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
                              Text(model.title ?? '-', style: Theme.of(context).textTheme.labelMedium),
                              Text(model.subTitle ?? '-', style: Theme.of(context).textTheme.labelMedium),
                            ]),
                          ),
                          onTap: () async {
                            await AppManager().deleteUser();
                            await HttpManager().saveEnvironment(model.value);
                            exit(0);
                          },
                        );
                      },
                      separatorBuilder: (BuildContext context, int index) => Divider(height: 48.w),
                      itemCount: hostList.length,
                    ),
                  );
                },
              );
            },
          ),
        ]);
      }
      _settingsList.add(
        ListTitleModel(
          id: 3,
          title: '退出登录',
          onTap: () {
            MyDialog.showWaringDialog(context, content: '确定退出账号吗？').then((value) {
              if (value == true) {
                MineApi.logOut();
                AppManager().deleteUser();
                EasyLoading.showToast('退出成功');
              }
            });
          },
        ),
      );
      setState(() {});
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Theme.of(context).colorScheme.background,
      padding: const EdgeInsets.symmetric(horizontal: 160).w,
      child: Column(children: [
        Image.asset(AssetsPath.imagePath('icon_logo_text', directory: 'logo'), width: 480.w, height: 150.w),
        Padding(padding: const EdgeInsets.only(top: 48, bottom: 100).w, child: Text('当前版本：${_currentVersion ?? '-'}', style: Theme.of(context).textTheme.labelMedium)),
        Expanded(
          child: ListView.separated(
            physics: const ClampingScrollPhysics(),
            itemBuilder: (BuildContext context, int index) {
              return InkWell(
                child: Padding(
                  padding: const EdgeInsets.symmetric(vertical: 48).w,
                  child: Row(children: [
                    Text(_settingsList[index].title ?? '', style: Theme.of(context).textTheme.labelMedium),
                    const Spacer(),
                    if (_settingsList[index].value != null)
                      Padding(padding: const EdgeInsets.only(right: 24.0).w, child: Text(_settingsList[index].value, style: Theme.of(context).textTheme.labelMedium)),
                    Image.asset(AssetsPath.imagePath('icon_arrow_right'), width: 18.w, height: 36.w, color: Theme.of(context).textTheme.labelMedium?.color)
                  ]),
                ),
                onTap: _settingsList[index].onTap,
              );
            },
            separatorBuilder: (BuildContext context, int index) => const Divider(),
            itemCount: _settingsList.length,
          ),
        ),
      ]),
    );
  }
}
